import json

from blueapps.account.decorators import login_exempt
from django.conf import settings
from django.contrib.auth.hashers import make_password
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.utils.crypto import pbkdf2
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

from blogs.forms import LoginForm, CreateUserForm, CreateArticleForm
from blogs.models import User, Post


def success(data={}):
    return {
        "result": True,
        "message": "success",
        "data": data,
        "code": 0
    }


def fail(message, data={}):
    return {
        "result": False,
        "message": message,
        "data": data,
        "code": 10002
    }


def parse_json(data):
    try:
        data = json.loads(data)
    except Exception as err:
        return False, str(err)
    return True, data


@login_exempt
@csrf_exempt
@require_POST
def login_views(request):
    leap, data = parse_json(request.body)
    if not leap:
        return JsonResponse(fail("参数格式错误, 请检查是否为json格式"))
    form = LoginForm(data=data)
    if form.is_valid():
        password = form.cleaned_data["password"]
        username = form.cleaned_data["username"]
        if User.objects.filter(password=make_password(password, settings.SECRET_KEY), username=username).exists():
            return JsonResponse(success())
        return JsonResponse(fail("用户不存在,请检查账号密码"))
    errors = form.errors.get_json_data()
    return JsonResponse(fail("参数错误,请检查参数", errors))


@method_decorator([csrf_exempt, login_exempt], name="dispatch")
class UserInfo(View):
    """
    用户信息
    get: 获取用户信息
    post: 添加用户信息
    """
    def get(self, request):
        user_id = request.GET.get("id")
        if not user_id:
            return JsonResponse(fail("参数缺少,请检查参数"))
        obj = User.objects.filter(id=user_id)
        if obj.exists():
            obj = obj.first()
            return JsonResponse(success(obj.to_dict()))
        return JsonResponse(fail("用户不存在,请检查参数"))

    def post(self, request):
        leap, data = parse_json(request.body)
        if not leap:
            return JsonResponse(fail("参数格式错误, 请检查是否为json格式"))
        form = CreateUserForm(data=data)
        if form.is_valid():
            obj = User.objects.create(**form.cleaned_data)
            return JsonResponse(success(obj.to_dict()))
        errors = form.errors.get_json_data()
        return JsonResponse(fail("参数错误,请检查参数", errors))


@method_decorator([csrf_exempt, login_exempt], name="dispatch")
class ArticleView(View):
    """
    文章
    get: 获取文章
    post: 添加文章
    """

    def get(self, request):
        user_id = request.GET.get("user_id")
        if not user_id:
            return JsonResponse(fail("参数缺少,请检查参数"))
        querysets = Post.objects.filter(user_id=user_id)
        posts = [obj.to_dict() for obj in querysets]
        return JsonResponse(success({"count": querysets.count(), "data": posts}))

    def post(self, request):
        leap, data = parse_json(request.body)
        if not leap:
            return JsonResponse(fail("参数格式错误, 请检查是否为json格式"))
        form = CreateArticleForm(data=data)
        if form.is_valid():
            obj = User.objects.filter(username=form.cleaned_data["username"])
            if not obj.exists():
                return JsonResponse(fail("用户不存在,请检查参数"))
            user = obj.first()
            querset = Post.objects.create(
                user=user,
                title=form.cleaned_data["title"],
                content=form.cleaned_data["content"]
            )
            return JsonResponse(success(querset.to_dict()))
        errors = form.errors.get_json_data()
        return JsonResponse(fail("参数错误,请检查参数", errors))



